package pl.enigmatic.parser.string.pl.edu.enigma.time;

import java.util.HashSet;
import java.util.Set;

import pl.enigmatic.time.RepeatBehavior;
import pl.enigmatic.util.Strings;
import pl.enigmatic.parser.string.Converter;
import pl.enigmatic.parser.string.custom.TimeSecondsDoubleConverter;
import pl.enigmatic.parser.string.java.lang.DoubleConverter;


public class RepeatBehaviorConverter extends Converter<RepeatBehavior> {

	private final DoubleConverter doubleConverter = new DoubleConverter();
	private final TimeSecondsDoubleConverter timeConverter = new TimeSecondsDoubleConverter();
	private final Set<String> forever = new HashSet<String>();

	public RepeatBehaviorConverter() {
		forever.add(RepeatBehavior.Type.FOREVER.toString().toLowerCase());
		forever.add("always");
		forever.add("infinite");
		forever.add("inf");
	}

	@Override
	public RepeatBehavior convert(final String value) {
		if (Strings.nonEmpty(value)) {
			if (forever.contains(value.toLowerCase())) {
				return RepeatBehavior.FOREVER;
			} else if (Strings.ending(value, 1).equalsIgnoreCase("x")) {
				return RepeatBehavior.createCount(doubleConverter.convert(Strings.beginning(value, 1)));
			} else {
				return RepeatBehavior.createDuration(timeConverter.convert(value));
			}
		}
		return null;
	}

	@Override
	public String convertBack(final RepeatBehavior value) {
		if (value.isForever()) {
			return RepeatBehavior.Type.FOREVER.toString().toLowerCase();
		} else if (value.hasDuration()) {
			return timeConverter.convertBack(value.getDuration());
		} else {
			return doubleConverter.convertBack(value.getCount()) + "x";
		}
	}

}
